var express = require('express');
var router = express.Router();
const {
    Chapter,
    Course
} = require('../../models');
const {
    Op
} = require('sequelize');
const { success, error, notFound, formatPagination } = require('../../utils/response');
const { filterBody, getPaginationParams } = require('../../utils/filter');

// 获取章节查询配置
const getCourseQueryOptions = (query = {}) => {
    const { currentPage, pageSize, offset } = getPaginationParams(query);
    
    const options = {
        attributes: { exclude: ['courseId'] },
        include: [
            {
                model: Course,
                as: 'course',
                attributes: ['id', 'name']
            }
        ],
        order: [['rank', 'ASC'], ['id', 'ASC']]
    };

    // 如果需要分页
    if (currentPage && pageSize) {
        options.limit = pageSize;
        options.offset = offset;
    }

    // 构建查询条件
    const where = {
        courseId: query.courseId // courseId 必填，在路由层已验证
    };

    // 标题模糊查询
    if (query.title) {
        where.title = {
            [Op.like]: `%${query.title}%`
        };
    }

    options.where = where;

    return options;
};

/* GET home page. */
// 获取章节列表
/**
 * @api {get} /admin/chapters 获取章节列表
 * @apiGroup Chapters
 * @apiVersion 1.0.0
 * @apiDescription 获取章节列表
 * @apiPermission 后台管理员
 * @apiParam {Number} courseId 课程ID（必填）
 * @apiParam {Number} [currentPage] 当前页码
 * @apiParam {Number} [pageSize] 每页条数
 * @apiParam {String} [title] 章节标题（模糊查询）
 */
router.get('/', async function (req, res, next) {
    try {
        const { courseId } = req.query;
        
        // 验证课程ID是否存在
        if (!courseId) {
            return res.json(error('课程ID不能为空', 400));
        }

        const { currentPage, pageSize } = getPaginationParams(req.query);
        const queryOptions = getCourseQueryOptions(req.query);
        
        const {
            rows,
            count
        } = await Chapter.findAndCountAll(queryOptions);
        
        res.json(success(formatPagination(rows, count, currentPage, pageSize), '查询成功'));
    } catch (err) {
        console.error('章节查询失败:', err);
        res.json(error(err.message || '查询失败', 500));
    }
});

// 查询章节详情
/**
 * @api {get} /admin/chapters/:id 查询章节详情
 * @apiGroup Chapters
 * @apiVersion 1.0.0
 */
router.get('/:id', async function (req, res, next) {
    try {
        const { id } = req.params;
        const queryOptions = getCourseQueryOptions();
        const chapter = await Chapter.findByPk(id, queryOptions);
        
        if (!chapter) {
            return res.status(404).json(notFound('章节'));
        }
        res.json(success(chapter, '查询成功'));
    } catch (err) {
        res.json(error('查询失败', 500, err.message));
    }
});

// 创建章节
/**
 * @api {post} /admin/chapters/save 创建章节
 * @apiGroup Chapters
 * @apiVersion 1.0.0
 */
router.post('/save', async function (req, res, next) {
    try {
        const body = filterBody(req.body, 'Chapter');
        const chapter = await Chapter.create(body);
        res.status(201).json(success(chapter, '创建成功', 201));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('创建失败', 400, errors));
        }
        res.json(error('创建失败'));
    }
});

//删除章节
/**
 * @api {delete} /admin/chapters/:id 删除章节
 * @apiGroup Chapters
 * @apiVersion 1.0.0
 */
router.delete('/:id', async function (req, res, next) {
    try {
        const {
            id
        } = req.params;
        const chapter = await Chapter.findByPk(id);
        if (!chapter) {
            return res.status(404).json(notFound('章节'));
        }
        await chapter.destroy();
        res.json(success(null, '删除成功', 200));
    } catch (err) {
        res.json(error('删除失败', 500, err.message));
    }
});

// 更新章节
/**
 * @api {post} /admin/chapters/update 更新章节
 * @apiGroup Chapters
 * @apiVersion 1.0.0
 * 
 */
router.post('/update', async function (req, res, next) {
    try {
        const {
            id
        } = req.body;
        const chapter = await Chapter.findByPk(id);
        if (!chapter) {
            return res.status(404).json(notFound('章节'));
        }
        const updateData = filterBody(req.body, 'Chapter');
        await chapter.update(updateData);
        res.json(success(chapter, '更新成功'));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('更新失败', 400, errors));
        }
        res.json(error('更新失败'));
    }
});
module.exports = router;